package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.aop.Aopannotation;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    //用户下单
    @PostMapping("/submit")
    @Aopannotation(type = "用户下单")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);

        orderService.submit(orders);
        return R.success("下单成功");
    }
    //查询历史订单
    @GetMapping("/userPage")
    public R<Page> userPage(int page,int pageSize){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        Long id = BaseContext.getCurrentId();
        lqw.eq(Orders::getUserId,id);
        lqw.orderByDesc(Orders::getOrderTime);
        orderService.page(ordersPage);

        BeanUtils.copyProperties(ordersPage,orderDtoPage,"records");
        List<Orders> records = ordersPage.getRecords();
        ArrayList<OrderDto> records2 = new ArrayList<>();
        for (Orders record : records) {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(record,orderDto);
            LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(OrderDetail::getOrderId,record.getId());

            List<OrderDetail> list = orderDetailService.list(lqw2);
            if (list!=null) {

                orderDto.setOrderDetails(list);
            }
            records2.add(orderDto);
        }
        orderDtoPage.setRecords(records2);
        return R.success(orderDtoPage);
    }
}